package space.cloaking.ext.tomcat;

import org.apache.catalina.loader.WebappClassLoader;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;

public class ConfigurableWebappClassLoader extends WebappClassLoader {

    private static final Log LOG = LogFactory.getLog(ConfigurableWebappClassLoader.class);

    private ClassLoader mConfigDelegate;

    public ConfigurableWebappClassLoader() {}

    public ConfigurableWebappClassLoader(ClassLoader parent) {
        super(parent);
    }

    void setConfigDelegate(ClassLoader configDelegate) {
        mConfigDelegate = configDelegate;
    }

    @Override
    public URL getResource(String name) {
        if(null != mConfigDelegate) {
            URL url = mConfigDelegate.getResource(name);
            if(null != url) {
                return url;
            }
        }

        return super.getResource(name);
    }

    @Override
    public InputStream getResourceAsStream(String name) {
        if(null != mConfigDelegate) {
            InputStream inputStream = mConfigDelegate.getResourceAsStream(name);
            if(null != inputStream) {
                return inputStream;
            }
        }

        return super.getResourceAsStream(name);
    }

    @Override
    public Enumeration<URL> getResources(String name) throws IOException {
        if(null != mConfigDelegate) {
            try {
                Enumeration<URL> enumeration = mConfigDelegate.getResources(name);
                if(enumeration.hasMoreElements()) {
                    return enumeration;
                }
            } catch(IOException e) { /* Ignore */ }
        }

        return super.getResources(name);
    }
}
